package com.lambkit.plugin.registry;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.lambkit.core.Lambkit;
import com.lambkit.core.registry.RegisterClient;
import com.lambkit.core.registry.ServiceInstance;
import com.lambkit.core.registry.ServiceInstanceListVo;
import com.lambkit.core.rpc.RpcConfig;

import java.util.Map;

/**
 * @author yangyong(孤竹行)
 */
public class LambkitRegisterClient implements RegisterClient {

    private String registerCenterAddress;

    @Override
    public ServiceInstance discover(String name) {
        String registryAddress = getRegisterCenterAddress();
        ServiceInstanceListVo serviceInstanceListVo = new ServiceInstanceListVo();
        String serviceName = name;
        String groupName = null;
        String namespace = null;
        if(name.indexOf("@") > 0) {
            String[] name1s = name.split("@");
            groupName = name1s[0];
            serviceName = name1s[1];
            if(groupName.indexOf("#") > 0) {
                String[] name2s = groupName.split("#");
                namespace = name2s[0];
                groupName = name2s[1];
            }
        }
        serviceInstanceListVo.setNamespaceId(namespace);
        serviceInstanceListVo.setGroupName(groupName);
        serviceInstanceListVo.setServiceName(serviceName);
        serviceInstanceListVo.setHealthyOnly(true);
        Map<String, Object> paramMap = BeanUtil.beanToMap(serviceInstanceListVo);
        String result = HttpUtil.get(registryAddress + "/lambkit/register/instance/list", paramMap);
        return null;
    }

    @Override
    public void registry(ServiceInstance serviceInstance) {
        String registryAddress = getRegisterCenterAddress();
        Map<String, Object> paramMap = BeanUtil.beanToMap(serviceInstance);
        String result = HttpUtil.get(registryAddress + "/lambkit/register/instance", paramMap);
        //
    }

    public String getRegisterCenterAddress() {
        if(StrUtil.isBlank(registerCenterAddress)) {
            RpcConfig rpcConfig = Lambkit.config(RpcConfig.class);
            return rpcConfig.getRegistryAddress();
        }
        return registerCenterAddress;
    }

    public void setRegisterCenterAddress(String registerCenterAddress) {
        this.registerCenterAddress = registerCenterAddress;
    }
}
